package com.sweets.look.database;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.URLUtil;

import com.sweets.look.R;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.browser.FetchUrlMimeType;
import com.sweets.look.ui.browser.WebAddress;
import com.sweets.look.util.ViewUtils;

public class DownloadHandler {

    private static String encodePath(String path) {
        int v9 = 124;
        int v8 = 93;
        int v7 = 91;
        int v4 = 0;
        char[] v1 = path.toCharArray();
        int v2 = 0;

        int v5 = 0;
        while (true) {
            if (v5 < v1.length) {
                int v0 = v1[v5];
                if (v0 != v7 && v0 != v8 && v0 != v9) {
                    ++v5;
                    continue;
                }
                v2 = 1;
            }
            break;
        }
        if (v2 != 0) {
            StringBuilder v3 = new StringBuilder("");
            v5 = v1.length;
            while (v4 < v5) {
                char v0_1 = v1[v4];
                if (v0_1 == v7 || v0_1 == v8 || v0_1 == v9) {
                    v3.append('%');
                    v3.append(Integer.toHexString(v0_1));
                } else {
                    v3.append(v0_1);
                }

                ++v4;
            }

            path = v3.toString();
        }

        return path;
    }

    /**
     * @param activity
     * @param url
     * @param userAgent
     * @param contentDisposition
     * @param mimetype
     * @param privateBrowsing
     * @param fileName
     */
    public static void onDownloadStart(Activity activity, String url, String userAgent, String contentDisposition,
                                       String mimetype, boolean privateBrowsing, String fileName) {
        if (contentDisposition == null || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.setDataAndType(Uri.parse(url), mimetype);
            intent.addFlags(268435456);//268435456
            ResolveInfo resolveInfo = activity.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);//65536
            if (resolveInfo != null) {
                ComponentName componet = activity.getComponentName();
                if (componet.getPackageName().equals(resolveInfo.activityInfo.packageName)) {
                    if (!componet.getClassName().equals(resolveInfo.activityInfo.name)) {
                        try {
                            activity.startActivity(intent);
                            return;
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    }

                } else {
                    try {
                        activity.startActivity(intent);
                        return;
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        onDownloadStartNoStream(activity, url, userAgent, contentDisposition, mimetype,
                privateBrowsing, fileName);
    }

    /**
     * 下载
     * @param activity
     * @param url
     * @param userAgent
     * @param contentDisposition
     * @param mimetype
     * @param privateBrowsing
     * @param fileName
     */
    private static void onDownloadStartNoStream(final Activity activity, String url, String userAgent, String
            contentDisposition, String mimetype, boolean privateBrowsing, String fileName) {
        final DownloadManager.Request request;
        String v16;
        String v14;
        String v9 = fileName != null ? fileName : URLUtil.guessFileName(url, contentDisposition, mimetype);
        String v15 = Environment.getExternalStorageState();
        if (!v15.equals("mounted")) {
            if (v15.equals("shared")) {
                v14 = activity.getString(R.string.download_sdcard_busy_dlg_msg);
                v16 = activity.getString(R.string.download_sdcard_busy_dlg_title);
            } else {
                v14 = activity.getString(R.string.download_no_sdcard_dlg_msg);
                v16 = activity.getString(R.string.download_no_sdcard_dlg_title);
            }

            ViewUtils.createInformativeDialog(activity, v16, v14);
            return;
        }
        WebAddress webAddress;
        try {
            webAddress = new WebAddress(url);
            webAddress.setPath(DownloadHandler.encodePath(webAddress.getPath()));
        } catch (Exception v10) {
            return;
        }

        String v6 = webAddress.toString();
        try {
            request = new DownloadManager.Request(Uri.parse(url));
        } catch (IllegalArgumentException e) {//仅可下载以 http 或 https 开头的链接地址
            ViewUtils.showToast(activity.getString(R.string.cannot_download), activity);
            return;
        }

        request.setMimeType(mimetype);
        request.setDestinationInExternalPublicDir(PreferenceManager.getInstance().getDownloadDirectory(),
                v9);
        request.allowScanningByMediaScanner();
        request.setTitle(v9);
        request.setDescription(url);
        String cookies = CookieManager.getInstance().getCookie(url);
        request.addRequestHeader("cookie", cookies);
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//1
        if (mimetype != null) {
            new Thread() {
                public void run() {
                    DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
                    try {
                        manager.enqueue(request);
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } else if (!TextUtils.isEmpty(v6)) {
            new FetchUrlMimeType(activity, request, v6, cookies, userAgent, v9).start();
        } else {
            return;
        }
        //正在开始下载
        ViewUtils.showToast(activity.getString(R.string.download_pending), activity);
    }
}

